package com.cg.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 发送邮件工具包
 */
@Component
public class MailUtil {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送短信
     * @param phone:收件人邮箱
     * @param title:标题
     * @param center:内容
     */
    public void send(String phone,String title,String center){
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message);

        try {
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(phone);
            mimeMessageHelper.setSubject(title);
            mimeMessageHelper.setText(center);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }


    /**
     * 邮箱正则表达式验证
     */
    private static final Pattern PATTERN = Pattern.compile("^\\w+@(\\w+\\.)+[a-z]{2,3}$");

    /**
     * 检查邮箱地址是否可用
     * @param email 邮箱地址
     * @return true：邮箱地址格式合法；false：邮箱地址格式不合法
     */
    public boolean checkEmail(String email) {
        Matcher matcher = PATTERN.matcher(email);
        return matcher.matches();
    }
}
